package com.issac.vhr.config;

import com.issac.vhr.entity.Menu;
import com.issac.vhr.entity.Role;
import com.issac.vhr.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
/*
*   权限访问类，根据用户传来的请求地址  分析出请求需要的角色
*
*
*
* */

@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    MenuService menuService;
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //当前请求地址
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        //每个请求都要加载一次，所以应当在方法上打Spring Cache注解 @Cacheable
        //跟数据库匹配
        List<Menu> allMenuWithRoles = menuService.getAllMenuWithRoles();
        for (Menu menu:allMenuWithRoles) {
            if (antPathMatcher.match(menu.getUrl(),requestUrl)){
                List<Role> roles = menu.getRoles();
                String [] str = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    str[i] = roles.get(i).getName();
                }
                return SecurityConfig.createList(str);
            }
        }
        //没有匹配上路径,给一个ROLE_LOGIN标记 代表登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
